import mongoose from "mongoose";

const customerSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      trim: true,
      maxlength: 50,
    },
    alias: {
      type: String,
      trim: true,
      maxlength: 50,
      default: "",
    },
    phone: {
      type: String,
      required: true,
      trim: true,
      match: /^1[3-9]\d{9}$/,
    },
    wechat: {
      type: String,
      trim: true,
      maxlength: 50,
      default: "",
    },
    alipay: {
      type: String,
      trim: true,
      maxlength: 50,
      default: "",
    },
    bankCard: {
      type: String,
      trim: true,
      maxlength: 30,
      default: "",
    },
    bankName: {
      type: String,
      trim: true,
      maxlength: 100,
      default: "",
    },
    idCardFront: {
      type: String,
      default: "",
    },
    idCardBack: {
      type: String,
      default: "",
    },
    status: {
      type: String,
      enum: ["active", "inactive"],
      default: "active",
    },
  },
  {
    timestamps: true,
  }
);

// 创建复合唯一索引：姓名+手机号
customerSchema.index({ name: 1, phone: 1 }, { unique: true });

// 创建文本搜索索引
customerSchema.index({
  name: "text",
  alias: "text",
  phone: "text",
  wechat: "text",
});

// 添加虚拟字段用于显示完整信息
customerSchema.virtual("displayName").get(function () {
  return this.alias ? `${this.name}(${this.alias})` : this.name;
});

// 确保虚拟字段被序列化
customerSchema.set("toJSON", { virtuals: true });
customerSchema.set("toObject", { virtuals: true });

export default mongoose.model("Customer", customerSchema);
